<template>
  <el-dialog v-model="dialogVisible" title="添加历史学员" width="80%" :before-close="handleClose">
    <el-form :inline="true" :model="formInline" class="grids gridColumns5" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="formInline.name" placeholder="姓名" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="formInline.mobile" placeholder="联系电话" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="班级">
        <classQuery v-model="formInline.classId"></classQuery>
      </el-form-item>
      <el-form-item label="身份证">
        <el-input v-model="formInline.identityCard" placeholder="身份证" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="所在企业">
        <el-input v-model="formInline.enterprise" placeholder="所在企业" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="工作年限">
        <el-select v-model="formInline.workYears" placeholder="请选择工作年限" @change="onSubmit">
          <el-option v-for="(item,index) in workYears.split(',')" :key="index" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="最高学历">
        <el-input v-model="formInline.education" placeholder="最高学历" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="毕业专业">
        <el-input v-model="formInline.graduationMajor" placeholder="毕业专业" clearable @change="onSubmit" />
      </el-form-item>
      <el-form-item label="报名所属">
        <dictSelect v-model="formInline.affiliation" dictCode="registration_affiliation" multiple="1"></dictSelect>
      </el-form-item>
      <el-form-item label="获证情况">
        <el-select v-model="formInline.isExamination" collapse-tags collapse-tags-tooltip :max-collapse-tags="2" placeholder="请选择获证情况" multiple @change="onSubmit">
          <el-option label="获证" :value="1" />
          <el-option label="未获证" :value="0" />
          <el-option label="缺考" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="init">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="tableRef" size="small" v-loading="loading" :data="tableParams.rows" max-height="50vh" @select-all="selectAll" @select="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="姓名" prop="user_Info.baseInfo.name" width="80" fixed="left">
        <template #default="scope">
          <div class="flex alignCenter name">
            {{field_format(scope.row,'name')}}
            <div v-if="scope.row.source" class="source">团</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="120" prop="user_Info.baseInfo.mobile">
        <template #default="scope">
          {{field_format(scope.row,'mobile')}}
        </template>
      </el-table-column>
      <el-table-column label="班级名称" width="300" prop="class_Info.className">
        <template #default="scope">
          <div class="className" @click="proxy.$utils.toLink(`/classManage/classDetails?classId=${scope.row.classId}`)">{{scope.row.class_Info.className}}</div>
        </template>
      </el-table-column>
      <el-table-column label="到课率" prop="name" width="100">
        <template #default="scope">
          <el-tooltip class="box-item" v-if="scope.row.userState==0" effect="dark" :content="`停课日期 ${scope.row.suspensionClassDate}`" placement="top">
            <div style="color: #8530F5;">停课</div>
          </el-tooltip>
          <div v-else>{{toClassPro(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column label="获证情况" prop="name" width="100">
        <template #default="scope">
          <div v-if="scope.row.isExamination==0" style="color:#A51D1B">未获证</div>
          <div v-else-if="scope.row.isExamination==1" style="color:#3B9A66">获证</div>
          <div v-else-if="scope.row.isExamination==2" style="color:#F5C73C">缺考</div>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{getGenderByIdCard(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.identityCard" label="身份证号" width="180">
        <template #default="scope">
          {{field_format(scope.row,'identityCard')}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.enterprise" label="所在企业名称" width="350" show-overflow-tooltip>
        <template #default="scope">
          {{field_format(scope.row,'enterprise')}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.workYears" label="累计工作年限" width="120">
        <template #default="scope">
          {{field_format(scope.row,'workYears')}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.education" label="最高学历" width="250">
        <template #default="scope">
          {{field_format(scope.row,'education')}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.graduationMajor" label="毕业专业" width="250">
        <template #default="scope">
          {{field_format(scope.row,'graduationMajor')}}
        </template>
      </el-table-column>
      <el-table-column prop="user_Info.baseInfo.employed_Status" label="就业状态" width="100">
        <template #default="scope">
          {{field_format(scope.row,'employed_Status')}}
        </template>
      </el-table-column>
      <el-table-column label="联系地址" width="400">
        <template #default="scope">
          {{contact_address_format(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="班级备注" width="250" />
      <el-table-column label="报名所属" width="150" align="center">
        <template #default="scope">
          {{affiliation_format(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column label="结业时间" width="120" align="center" fixed="right">
        <template #default="scope">
          {{proxy.$utils.dateTimeFormateFn(scope.row.graduationTime)}}
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="tableParams['total']" :total="tableParams['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirm" :loading="pageLoading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
let props = defineProps(["classInfo"]);
const emit = defineEmits(["fatherMethods"]);

let dialogVisible = ref(false);
let formInline = ref({
  name: "",
  mobile: "",
  classId: "",
  type: "history",
  identityCard: "",
  enterprise: "",
  workYears: "",
  education: "",
  graduationMajor: "",
  affiliation: "",
  isExamination: null,
  needSourceFile: 0, //是否需要查线下导入学员
  pageIndex: 1,
  pageSize: 50,
});
let tableParams = ref({});
let loading = ref(false);
let workYears = ref(
  "应届毕业年,不满1年,满1年,满2年,满3年,满4年,满5年,满6年,满7年,满8年,满9年,满10年及以上"
);
let selected = ref([]);
let pageLoading = ref(false);

let handleSelect = computed(() => {
  let arr = [];
  let list = proxy.$utils.deepcopy(selected.value);
  list.forEach((element) => {
    let obj = {
      curriculum_id: element.curriculum_id, //课程id
      userId: element.userId, //用户id
      classId: element.classId, //班级id
      orderId: element.orderId, //订单id
    };
    arr.push(obj);
  });
  return proxy.$utils.uniqueByFields(arr, "classId", "orderId");
});

function selectAll(array) {
  if (array.length) {
    array.forEach((element) => {
      if (proxy.$utils.isFieldEqual(selected.value, "_id", element._id)) {
      } else {
        selected.value.push(element);
      }
    });
  } else {
    tableParams.value.rows.forEach((element) => {
      let index = proxy.$utils.findIndexByField(
        selected.value,
        "_id",
        element._id
      );
      if (index != -1) selected.value.splice(index, 1);
    });
  }
}

function handleSelectionChange(e, k) {
  if (proxy.$utils.isFieldEqual(e, "_id", k._id)) {
    selected.value.push(k);
  } else {
    let index = proxy.$utils.findIndexByField(selected.value, "_id", k._id);
    if (index != -1) selected.value.splice(index, 1);
  }
}

function onSubmit() {
  formInline.value.pageIndex = 1;
  getInfo();
}

function handleClose() {
  emit("fatherMethods");
  init();
  selected.value = [];
  dialogVisible.value = false;
}

function open() {
  getInfo();
  dialogVisible.value = true;
}

function field_format(item, key) {
  let row = item.source ? item.user_data : item.user_Info.baseInfo;
  return row[key];
}

function contact_address_format(row) {
  for (let index = 0; index < row.B3_data.length; index++) {
    const element = row.B3_data[index];
    if (element.userId == row.userId) {
      return element.address;
    }
  }
}

function affiliation_format(item) {
  let row = item.source ? item.user_data : item.user_Info.baseInfo;
  if (!row.affiliation) return "-";
  if (proxy.$utils.isString(row.affiliation)) {
    return row.affiliation;
  } else if (proxy.$utils.isArrayOrJsonArray(row.affiliation)) {
    return row.affiliation.toString();
  } else {
    return "-";
  }
}

function toClassPro(row) {
  let total = row.schedule_data.length;
  let arr = [...row.signIn_data];
  let list = [];
  arr.forEach((element) => {
    if (element.userId == row.userId) {
      if (element.status == 1) {
        list.push(element);
      }
    }
  });
  return (list.length / total) * 100 + "%";
}

function getGenderByIdCard(item) {
  let row = item.source ? item.user_data : item.user_Info.baseInfo;
  let idCard = row.identityCard;
  if (!idCard || idCard.length !== 18) return "-";
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

async function getInfo() {
  try {
    loading.value = true;
    tableParams.value = await proxy.$apis.classStudentManage({
      data: formInline.value,
    });
    nextTick(() => {
      selected.value.forEach((element) => {
        let a = tableParams.value.rows.find((el) => {
          return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
        });
        if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
      });
    });
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function init() {
  formInline.value = {
    name: "",
    mobile: "",
    classId: "",
    type: "history",
    identityCard: "",
    enterprise: "",
    workYears: "",
    education: "",
    graduationMajor: "",
    affiliation: "",
    isExamination: null,
    needSourceFile: 0, //是否需要查线下导入学员
    pageIndex: 1,
    pageSize: 50,
  };
  getInfo();
}

async function confirm() {
  try {
    pageLoading.value = true;
    let list = proxy.$utils.deepcopy(handleSelect.value);
    if (!list.length) return proxy.$utils.showToast("请选择学生", 0);
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      //userState: 1, // 停课状态 0:正常 1:停课
      let obj = {
        userId: element.userId,
        userState: 1,
        classId: props.classInfo._id,
      };
      //查询到符合条件的订单
      let orderId = await proxy.$apis.classStudent({
        type: "add-historical-students",
        data: {
          classId: props.classInfo._id,
          userId: element.userId,
        },
      });
      obj["orderId"] = orderId;
      await proxy.$apis.classStudent({ type: "add", data: obj });
    }
    proxy.$utils.showToast("添加成功");
    handleClose();
  } catch (error) {
  } finally {
    pageLoading.value = false;
  }
}

defineExpose({ open });
</script>



<style lang="scss" scoped>
</style>


